﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace NinjaToolbox.SubComponentModule.Example
{
    public class SE2_Jump : SubComponent<SE2_Jump_Model>
    {
        MonoBehaviour mCacheMonoBehaviour;
        Animator mCacheAnimator;
        Transform mCacheTransform;
        SE2_FSM mFSM;

        bool mIsJumping;


        protected override void SubComponent_OnEnable()
        {
            base.SubComponent_OnEnable();

            mCacheMonoBehaviour = mContext.Owner as MonoBehaviour;

            mCacheTransform = mCacheMonoBehaviour.transform;
            mCacheAnimator = mCacheMonoBehaviour.GetComponentInChildren<Animator>();
            mFSM = mContext.Container.GetSubComponent<SE2_FSM>();
        }

        protected override void SubComponent_Update()
        {
            base.SubComponent_Update();

            if (mFSM.CurrentState != SE2_FSM.EState.Idle
                && mFSM.CurrentState != SE2_FSM.EState.Runing
                && mFSM.CurrentState != SE2_FSM.EState.Jump)
            {
                return;
            }

            var isJump = false;

            if (Input.GetKeyUp(KeyCode.K))
                isJump = true;

            if (isJump && !mIsJumping)
            {
                mIsJumping = true;

                mCacheMonoBehaviour.StartCoroutine(DoJump());
                mFSM.CurrentState = SE2_FSM.EState.Jump;
            }
        }

        IEnumerator DoJump()
        {
            mCacheAnimator.Play(Model.jumpAnimKey);

            var upAxis = -Physics.gravity.normalized;

            var beginTime = Time.time;
            for (var duration = 1f; Time.time - beginTime <= duration;)
            {
                mCacheTransform.position += upAxis * Model.jumpForce * Time.deltaTime;

                yield return null;
            }

            mIsJumping = false;
            mFSM.CurrentState = SE2_FSM.EState.Idle;
        }
    }
}
